import can
import cantools
import os



class BlfParser():
    def __init__(self,dbc_path,blf_path):
        self.__dbc_path = dbc_path
        self.__blf_path = blf_path
        self.blf_message_list = self.__get_message_data()
        self.db = None
        self.__load_dbc_files()

    def __get_message_data(self):
        log = can.BLFReader(self.__blf_path)
        msg_list = list(log) 
        return msg_list

    def __load_dbc_files(self):
        # 获取目录下所有.dbc后缀的文件
        file_names = [i for i in os.listdir(self.__dbc_path) if i[-4:] == ".dbc"]
        # 检查是否存在DBC文件
        if len(file_names) == 0:
            raise FileNotFoundError("the DBC file does't exits,check your path pls")
        else:
            # 遍历所有DBC文件
            for i in range(len(file_names)):
                if i == 0:
                    # 加载第一个DBC文件作为主数据库
                    self.db = cantools.database.load_file(self.__dbc_path + "/" + file_names[i])
                else:
                    # 将其他DBC文件添加到主数据库中
                    self.db.add_dbc_file(self.__dbc_path + "/" + file_names[i])
    
    def signal_parser(self,canmsg,signame):
        temp_msg = self.db.decode_message(canmsg.arbitration_id,canmsg.data)
        return temp_msg[signame]

    def msg_parser(self,canmsg):
        temp_msg = self.db.decode_message(canmsg.arbitration_id,canmsg.data)
        return temp_msg
    
